/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts, CallExpression, rule } from "qvog-dsl";

const SEVERITY = 2;
const DOC_PATH = 'docs/max-callback-depth-check.md';
const DESCRIPTION = 'Multi-level nested callback functions can lead to code that is difficult to maintain and understand (callback hell). It is recommended to use Promises, async/await, or extract callbacks into separate functions to improve code structure.';
const MAX_DEPTH = 3;

function findFunctionInArguments(node: ts.CallExpression): ts.FunctionExpression[] {
    let result:ts.FunctionExpression[] = [];
    let args = node.arguments;
    for (let arg of args) {
        if (ts.isFunctionExpression(arg)) {
            result.push(arg as ts.FunctionExpression);
        }
    }
    return result;
}


function findCallInStatements(node: ts.FunctionExpression): ts.CallExpression[] {
    let result: ts.CallExpression[] = [];
    let statements = node.body.statements;
    for (let stmt of statements) {
        if (ts.isExpressionStatement(stmt) && ts.isCallExpression((stmt as ts.ExpressionStatement).expression)) {
            let callExpr = (stmt as ts.ExpressionStatement).expression;
            result.push(callExpr as ts.CallExpression);
        }
    }
    return result;
}


function depthSearch(node: ts.CallExpression, depth: number): boolean {
    if (depth > MAX_DEPTH) {
        return true;
    }
    let result = false;
    let argFunc = findFunctionInArguments(node);
    for (let arg of argFunc) {
        let callExpr = findCallInStatements(arg);
        for (let call of callExpr) { 
            result = depthSearch(call, depth + 1);
            if (result) {
                return true;
            }
        }
    }
    return false;
}

export default rule()
    .match(CallExpression)
    .when((node): boolean => {
        return depthSearch(node, 0);
    })
    .report({
        severity: SEVERITY,
        description: DESCRIPTION,
        docPath: DOC_PATH,
        maxDepth: MAX_DEPTH
    });
    